package com.fowo.api.walmart.api;

import cn.hutool.core.text.csv.CsvReader;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.datainterface.constants.Constants;
import com.fowo.api.entity.Parilist;
import com.fowo.api.entity.ShopInfo;
import com.fowo.api.entity.TmpWalmartStock;
import com.fowo.api.mapper.ParilistMapper;
import com.fowo.api.mapper.ShopInfoMapper;
import com.fowo.api.service.impl.TmpWalmartStockServiceImpl;
import com.fowo.api.walmart.config.WalmartCsvReadConfig;
import com.fowo.api.walmart.util.WalmartUtil;
import com.squareup.okhttp.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;

@Component
@Slf4j
public class WalmartInventoryApi {

    @Resource
    private ShopInfoMapper shopInfoMapper;
    @Resource
    private ParilistMapper parilistMapper;
    @Resource
    private TmpWalmartStockServiceImpl tmpWalmartStockService;

    private static final String WFS_INVENTORY_URL = "https://marketplace.walmartapis.com/v3/report/wfs/getInventoryHealthReport";

    public void getInventoryReport() throws IOException {
        final List<ShopInfo> shopInfos = shopInfoMapper.selectList(Wrappers.lambdaQuery(ShopInfo.class)
                .eq(ShopInfo::getPlatform, "Walmart")
                .eq(ShopInfo::getSellerAuthStatus, "SQ01"));
        for(ShopInfo shopInfo : shopInfos){
            List<Parilist> parilists = parilistMapper.selectList(Wrappers.lambdaQuery(Parilist.class)
                    .eq(Parilist::getShopId,shopInfo.getId())
                    .eq(Parilist::getType,"1"));

            String token = WalmartUtil.getToken(shopInfo.getMarketplaceId(),shopInfo.getRefreshToken());
            Map<String,String> headers = new HashMap<>();
            headers.put("WM_SEC.ACCESS_TOKEN",token);
            headers.put("WM_SVC.NAME","Walmart Service Name");
            headers.put("WM_QOS.CORRELATION_ID", UUID.randomUUID().toString());
            HttpResponse response = HttpRequest.get(WFS_INVENTORY_URL)
                    .addHeaders(headers)
                    .execute();
            if(response.getStatus() == 200){
//                String contentDisposition = response.header("Content-Disposition");
//                String fileName = null;
//                if(contentDisposition != null && contentDisposition.contains("filename=")){
//                    fileName = contentDisposition.substring(contentDisposition.indexOf("filename=")+9).replace("\"","");
//                }
                final InputStream inputStream = response.bodyStream();
                Reader reader = new InputStreamReader(inputStream);
                final CsvReader csvReader = CsvUtil.getReader(reader,WalmartCsvReadConfig.setInventoryReadConfig());
                List<TmpWalmartStock> tmpList = new ArrayList<>();
                csvReader.read().getRows().forEach(csvRow->{
                    System.out.println(csvRow.toString());
                    TmpWalmartStock tmpWalmartStock = new TmpWalmartStock();
                    tmpWalmartStock.setGtin(csvRow.get(0).replace("=","").replaceAll("\"",""));
                    tmpWalmartStock.setItemId(csvRow.get(1));
                    tmpWalmartStock.setMsku(csvRow.get(2));
                    tmpWalmartStock.setTitle(csvRow.get(3));
                    tmpWalmartStock.setBrandName(csvRow.get(4));
                    tmpWalmartStock.setPlatformProductStatus(csvRow.get(5));
                    Integer availableQuantity = Integer.valueOf(csvRow.get(6));
                    tmpWalmartStock.setAvailableQuantity(availableQuantity);
                    tmpWalmartStock.setUnabledWarehousingQuantity(Integer.valueOf(csvRow.get(7)));
                    Integer inboundQuantity = Integer.valueOf(csvRow.get(8));
                    tmpWalmartStock.setInboundQuantity(inboundQuantity);
                    tmpWalmartStock.setQuantity(availableQuantity+inboundQuantity);
                    tmpWalmartStock.setAts03Months(Integer.valueOf(csvRow.get(16)));
                    tmpWalmartStock.setAts36Months(Integer.valueOf(csvRow.get(17)));
                    tmpWalmartStock.setAts69Months(Integer.valueOf(csvRow.get(18)));
                    tmpWalmartStock.setAts912Months(Integer.valueOf(csvRow.get(19)));
                    tmpWalmartStock.setAts1Years(Integer.valueOf(csvRow.get(20)));
                    tmpWalmartStock.setLast30DaysUnitsReceived(Integer.valueOf(csvRow.get(21)));
                    tmpWalmartStock.setLast30DaysPoUnits(Integer.valueOf(csvRow.get(22)));
                    tmpWalmartStock.setSid(shopInfo.getId());
                    tmpWalmartStock.setShopName(shopInfo.getShopName());

                    final Parilist parilist = parilists.stream().filter(p -> p.getMsku().equals(csvRow.get(2))).findFirst().orElse(null);
                    if(null != parilist){
                        tmpWalmartStock.setPid(parilist.getProductId());
                        tmpWalmartStock.setSku(parilist.getSku());
                        tmpWalmartStock.setProductName(parilist.getProductName());
                        tmpWalmartStock.setImg(parilist.getImg());
                    }
                    tmpWalmartStock.setCreateTime(new Date());
                    tmpWalmartStock.setLastUpdateTime(new Date());
                    tmpList.add(tmpWalmartStock);
                });
                tmpWalmartStockService.saveBatch(tmpList);
            }

        }
    }
}
